import datetime

from google.appengine.ext.webapp import template

from models import Quote

def calc_volatility_hist():
    pass

def calc_volatility_impl():
    pass

def get_black_scholes_pricing():
    pass

def get_expiry_date(letter, year_number):
    # Okreslenie miesiaca i ilosci dni w miesiacu:
    if letter in ['C', 'O']:
        month = 3
        days = 31
    elif letter in ['F', 'R']:
        month = 6
        days = 30
    elif letter in ['I', 'U']:
        month = 9
        days = 30
    elif letter in ['L', 'X']:
        month = 12
        days = 31
       
    # Aktualna data:
    current_date = datetime.date.today()
    # Wyliczenie roku:
    tmp = str(current_date.year)
    year_delta = int(year_number) - int(tmp[3])
    expiry_year = current_date.year + year_delta
       
    # Znalezienie ostaniego piatku miesiaca
    friday_weekday = 4
    tmp_date = datetime.date(expiry_year, month, days)
    weekday = tmp_date.weekday()
    if weekday >= friday_weekday:
        tmp_date = tmp_date - datetime.timedelta(weekday - 4)
    else:
        tmp_date = tmp_date - datetime.timedelta(weekday + 3)
     
    return tmp_date
    
class TestService(object):
    def pricing(self, argv):
        call_letters = ['C', 'F', 'I', 'L']
        put_letters = ['O', 'R', 'U', 'X']
    
        # Przygotowanie danych:
        query = Quote.all().filter("is_last =", True).filter("type =", "O")
        options = []
        for quote in query:
            option = { }            
            
            option['expiry'] = get_expiry_date(quote.name[4], quote.name[5])
            option['strike'] = int(quote.name[6:9]) * 10
            
            if quote.name[4] in call_letters:
                option['type'] = 'Call'
            elif quote.name[4] in put_letters:
                option['type'] = 'Put'
            else:
                option['type'] = 'Undef'
            
            option['name'] = quote.name
            option['open'] = quote.open
            option['high'] = quote.high
            option['low'] = quote.low
            option['close'] = quote.close
            option['volume'] = quote.volume
            option['lop'] = quote.lop
        
            options.append(option)
    
        template_values = {
            'options': options
        }
        
        return template.render('templates/parts/option-table-pricing.html', template_values)
